import queue
import cv2
from threading import Thread, Event
import time


class VideoCapture:

    def __init__(self, name):
        self.name = name
        self.cap = cv2.VideoCapture(self.name)
        self.frame_width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.frame_height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        self.q = queue.Queue()
        t = Thread(target=self._reader)
        t.daemon = True
        t.start()

    # read frames as soon as they are available, keeping only most recent one
    def _reader(self):
        while True:
            ret, frame = self.cap.read()
            if not ret:
                self.cap = cv2.VideoCapture(self.name)

            if not self.q.empty():
                try:
                    self.q.get_nowait()  # discard previous (unprocessed) frame
                except queue.Empty:
                    pass
            self.q.put(frame)

    def read(self):
        try:
            data = self.q.get()
        except:
            return None
        return data

    def getsize(self):
        return self.frame_width, self.frame_height
